package com.tpl.core.basedata.common.task;

import com.tpl.core.basedata.dao.TriggerTaskDao;
import com.tpl.core.entity.sys.TriggerTask;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;

import java.util.List;


/**
 * 默认任务，加载定时任务
 */
public class DefaultTask {

	private Log log = LogFactory.getLog(DefaultTask.class);
	@Autowired
	private TriggerTaskDao triggerTaskDao;
	@Autowired
	private Scheduler scheduler;
	
	public void init()throws Exception{
		try{
			List<TriggerTask> list = triggerTaskDao.getOnlineTaskList();
			log.info(""+list.size()+" jobs found in database");
			for(TriggerTask job:list){
				load(job);
			}
//			scheduler.unscheduleJob("initTrigger", Scheduler.DEFAULT_GROUP);
//			scheduler.deleteJob("initJob", Scheduler.DEFAULT_GROUP);
			log.warn("init step finished,all online-jobs loaded complete");
		}catch (Exception e) {
			log.error("Trigger Jobs loading failed:"+e.getCause());
			throw e;
		}
	}
	
	private void load(TriggerTask configure)throws Exception{
		String triggerName = "trigger"+configure.getId();
		String jobName = "job"+configure.getId();
	//	String listenerName = "listener"+configure.getId();
		MethodInvokingJobDetailFactoryBean factory = new MethodInvokingJobDetailFactoryBean();
		factory.setTargetObject(new TriggerTaskExecute());
		factory.setTargetMethod("execute");
		factory.setName(jobName);
		factory.setArguments(new Object[]{configure.getId(),configure.getSourceId(),configure.getSourceServiceName()});
		factory.setGroup("DEFAULT_GROUP");
		factory.afterPropertiesSet();
		JobDetail job = (JobDetail)factory.getObject();
//		CronTrigger trigger = new CronTrigger(triggerName,"DEFAULT_GROUP",configure.getCronExpression());
		//TaskFinishTriggerListener finishTriggerListener = new TaskFinishTriggerListener(listenerName);
//		trigger.setStartTime(new Date());
		//trigger.addTriggerListener(listenerName);
//		if(trigger.getFireTimeAfter(new Date())==null){
//			TaskUtil.stopTask(configure.getId());
//			return;
//		}
		//scheduler.addTriggerListener(finishTriggerListener);
//		scheduler.scheduleJob(job, trigger);
		log.info("Job loaded:"+configure.getName());
	}
	
	
	
}
